/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src.view.saving;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.primefaces.context.RequestContext;
import org.primefaces.event.CloseEvent;
import org.primefaces.event.SelectEvent;
import src.domain.finance.Bank;
import src.domain.saving.Savdepo;
import src.domain.saving.Saving;
import src.domain.security.Users;
import src.services.finance.BankModel;
import src.services.saving.SavdepoModel;
import src.services.saving.SavingModel;
import src.util.Messager;
import src.view.security.LoginBean;

/**
 *
 * @author jay
 */
@ManagedBean
@SessionScoped
public class SavdepoBean implements Serializable {

    //autocomlpit
    private Savdepo savdepo;  
    private List<SelectItem> availableGL;  
    private SavdepoModel savdepoHelper;
    private boolean editMode = false, authorized=false, insertionMode=false;
    private BigDecimal saldoAwal = BigDecimal.ZERO, saldoAkhir = BigDecimal.ZERO;
    private Integer branchId, bankId, glaccntId;
    private Users user;
    private String defaultButton="doNothingSavdepo";
    private boolean showLookup=false;
        
    public SavdepoBean() {
        super();
        ambilUser();
        this.savdepoHelper = new SavdepoModel();
        editMode = false;
        authorized = false;
    }
    
    private boolean cekConfig() {
        boolean complete=true;
        try {
            this.branchId = user.getBranch().getBranchId();
            
            this.bankId = user.getSavBankId(); 
            Bank bank = new BankModel().getById(bankId);
            this.glaccntId = bank.getGlaccountId(); 
            
        } catch (RuntimeException e) {complete=false;
        } finally {}
        
        if (this.branchId==null || this.bankId==null || this.glaccntId==null) complete=false;
        
        if(complete==false) Messager.showWarning("savingUnconfig");
        return complete;
    }

    public boolean isShowLookup() {
        return showLookup;
    }

    public void setShowLookup(boolean showLookup) {
        this.showLookup = showLookup;
    }
    
    public String getDefaultButton() {
        return defaultButton;
    }

    public void setDefaultButton(String defaultButton) {
        this.defaultButton = defaultButton;
    }
        
    public boolean isEditMode() {
        return editMode;
    }

    public boolean isAuthorized() {
        return authorized;
    }
    
    public Savdepo getSavdepo() {
        return savdepo;
    }

    public void setSavdepo(Savdepo savdepo) {
        this.savdepo = savdepo;
    }

    public List<SelectItem> getAvailableGL() {
        return availableGL;
    }

    public BigDecimal getSaldoAkhir() {
        return saldoAkhir;
    }

    public BigDecimal getSaldoAwal() {
        return saldoAwal;
    }

    public void getSavingSrc(String accntNo) {
        if ("null".equals(accntNo)) accntNo = savdepo.getSaving().getAccountNo();
        
        boolean found=false;
        if (accntNo!=null ) {
            this.saldoAwal = BigDecimal.ZERO;
            this.saldoAkhir = BigDecimal.ZERO;
            SavingModel helper = new SavingModel();
            Saving saving = helper.getByAccount(accntNo);
            if (saving==null) {
                this.savdepo.setSaving(new Saving());
                Messager.showWarning("accntNotFound");
                
            } else {
                found=true;
                this.savdepo.setSaving(saving);
                this.saldoAwal = savdepo.getSaving().getBalance();
                //this.defaultButton="submitSavdepo";
                this.defaultButton="doNothingSavdepo";
                
                if (savdepo.getAmount() != null) this.saldoAkhir = this.saldoAwal.add(savdepo.getAmount());
            }   
        }
        RequestContext.getCurrentInstance().addCallbackParam("success", found); 
    }
    
    public void calcSaldoAhir() {
        if (savdepo.getAmount() != null) 
            this.saldoAkhir = saldoAwal.add(savdepo.getAmount());
    }
        
    public void handleSavingSelected(SelectEvent event) {
        savdepo.setSaving((Saving) event.getObject());
    } 
    
    public void search() {}
        
    private void initForm() {
        this.editMode = true;
        this.authorized = true;
        showLookup=false;
        this.defaultButton="doNothingSavdepo";
        saldoAkhir= BigDecimal.ZERO;
        saldoAwal= BigDecimal.ZERO;
    }
        
    public final void newData() {  
        initForm();
        cekConfig();
        if (this.savdepo!=null) savdepo = null;
        
        this.savdepo = new Savdepo();
        this.savdepo.setBranchId(branchId);
        this.savdepo.setBankId(bankId);
        this.savdepo.setLinkGlaccountId(glaccntId);
        insertionMode = true;
    }
    
    private boolean validate() {
        Boolean hasil = true;
        Integer firstDeposit = savdepoHelper.count(savdepo.getSaving().getSavaccntId());
        BigDecimal amount = savdepo.getAmount();
        BigDecimal firstDepositAmt = savdepo.getSaving().getSavprod().getMinFirstDeposit();
        BigDecimal regDepositAmt = savdepo.getSaving().getSavprod().getMinRegDeposit();
        
        //validasi setoran pertama
        if(firstDeposit.equals(0)) {
            
            if(amount.compareTo(firstDepositAmt)==-1) {
                Messager.showWarning("savfirstDepositKurang");
                hasil=false;
            }
        }
                
        //validasi setoran selanjutnya
        else {
            if(amount.compareTo(regDepositAmt)==-1) {
                Messager.showWarning("savregulerDepositKurang");
                hasil=false;
            }
        } 
        
        if (hasil==true) hasil = cekConfig();
        
        return hasil;
    }
    
    private void validateLimit() {
        this.authorized = true;

        Integer authorizedId = savdepoHelper.authorized(savdepo.getSavdepoId());
        
        savdepo.setUserId(user.getUserId());
        savdepo.setAuthorizedId(authorizedId);
        
        //belum diotorisasi, cek validasi
        if (authorizedId == null) {
            BigDecimal ddAmount = savdepo.getAmount();
            BigDecimal ddAmountAlowed = user.getUgroup().getSavMaxDeposit();
            if(ddAmount.compareTo(ddAmountAlowed) >= 0) this.authorized=false;
            
            //jika dlm rage limit, authorizedId = userId
            else savdepo.setAuthorizedId(user.getUserId());
        }
        
        //men-triger history and balance
        savdepo.setPosted(authorized);
    }
        
    private void save() {
        validateLimit();
        
        boolean success = savdepoHelper.saveData(savdepo);
        //this.editMode = (!success || !authorized);
        this.editMode = (!success);
        Messager.showSaveUpdateStatus(success);     
        
        if (!authorized && success)
            Messager.showWarning("unauthorized");    
        
        //ngahaja. biar inputBox bisa ngisi klo eror
        if (!success) authorized = true;
        else {
            
            //kalo sukses & athorized....
            if (authorized) authorized = false;
        }    
        
        // re-insert
        if (!success && insertionMode) savdepo.setSavdepoId(null);
        else insertionMode = false;
        
        RequestContext.getCurrentInstance().addCallbackParam("success", success); 
    }
    
    public void delete() {
        boolean success;  
        success = savdepoHelper.deleteData(savdepo);
                
        this.editMode = !success;
        Messager.showDeleteStatus(success);     
    }
 
    public void trySave() {
        if (this.validate()) this.save();
    }
    
    public void handleCloseLookup(CloseEvent event) {
        this.showLookup=false;
    }
    
    private void ambilUser() {
        FacesContext context = FacesContext.getCurrentInstance();
        LoginBean logBean = (LoginBean) context.getApplication().evaluateExpressionGet(context, "#{loginBean}", LoginBean.class);
        this.user = logBean.getSelectedUser();
    }
 
}
